//
//  IMFileDownLoadController.m
//  wanzhaoIM
//
//  Created by wanzhao on 15/7/16.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "IMFileDownLoadController.h"
#import "ChildHoodService.h"
#import "IMPreviewFileController.h"
#import "CXmppRequestMgr.h"
#import "IMFowardController.h"
#import "ChildHoodService.h"
#import "MicroDef.h"
#import "UIUtil.h"
#import "Reachability.h"
#import "VoiceConverter.h"
#import "IMOtherOpenFileController.h"
#import "JKAlertDialog.h"
#import "MBProgressHUD+WZ.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "WZNavigationController.h"
#import "UIBarButtonItem+category.h"


@interface IMFileDownLoadController ()<UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) UIButton *downLoadButton;
@property (nonatomic, strong) UIButton *openButton;
@property (nonatomic, strong) UIButton *fowardButton;
@property (nonatomic, strong) UIButton *otherButton;
@property (nonatomic, strong) UIButton *oprateDownButton;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, copy) NSString *fileId;

//断点相关
@property (nonatomic, assign) double currentLenth;
@property (nonatomic, strong) NSData *currentData;
@property (nonatomic, strong) NSFileHandle *writeHandle;

@property (nonatomic, strong) UIButton *fileImgButton;
@property (nonatomic, strong) UILabel *discLabel;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, assign) BOOL isCanOpen;
@property (nonatomic, strong)  UIDocumentInteractionController *doInter;

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UILabel *progressLabel;

@end

@implementation IMFileDownLoadController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"文件预览"];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];

    
    
    self.fileImgButton = [[UIButton alloc] init];
    self.fileImgButton.backgroundColor = ClearColor;
    self.fileImgButton.userInteractionEnabled = NO;
    [self.view addSubview:self.fileImgButton];
    
    self.discLabel = [[UILabel alloc] init];
    self.discLabel.textColor = [UIColor grayColor];
    self.discLabel.font = [UIFont systemFontOfSize:14.0f];
    self.discLabel.backgroundColor = ClearColor;
    self.discLabel.numberOfLines = 0;
    self.discLabel.textAlignment = NSTextAlignmentCenter;
    self.discLabel.text = [NSString stringWithFormat:@"%.2fK  %@到期",self.chMessage.fileLenth.floatValue / 1024.0,[UIUtil getOverdueYMDHMSDateStringWithTimeStamp:self.chMessage.messageTime]];
    [self.view addSubview:self.discLabel];
    
    self.nameLabel = [[UILabel alloc] init];
    self.nameLabel.textColor = [UIColor blackColor];
    self.nameLabel.font = [UIFont systemFontOfSize:16.0f];
    self.nameLabel.backgroundColor = ClearColor;
//    if (self.chMessage.GroupId.length > 3) {
//        self.nameLabel.text = [UIUtil getGroupFileNameWithServerFileName:self.chMessage.fileName];
//    } else {
//        self.nameLabel.text = [UIUtil getFileNameWithServerFileName:self.chMessage.fileName];
//    }
    self.nameLabel.numberOfLines = 0;
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.nameLabel];
    
    
    self.progressLabel = [[UILabel alloc] init];
    self.progressLabel.textColor = [UIColor grayColor];
    self.progressLabel.font = [UIFont systemFontOfSize:14.0f];
    self.progressLabel.backgroundColor = ClearColor;
    self.progressLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.progressLabel];
    self.progressLabel.hidden = YES;
    
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.backgroundColor = ClearColor;
    self.progressView.trackTintColor = [UIColor lightGrayColor];
    self.progressView.transform = CGAffineTransformMakeScale(1.0f,2.0f);
    self.progressView.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
    self.progressView.hidden = YES;
    [self.view addSubview:self.progressView];


    NSString *fileId;
    NSString *fileName;
    
    if (self.chMessage.GroupId.length > 3) {
        if (self.chMessage.isMine == CHBubbleMessageTypeSended) {
            fileId = self.chMessage.GroupId;
        } else {
            fileId = self.chMessage.GroupId;
        }
        fileName = [UIUtil getGroupFileNameWithServerFileName:self.chMessage.fileName];
        
    } else {
        fileName = [UIUtil getFileNameWithServerFileName:self.chMessage.fileName];
        if (self.chMessage.isMine == CHBubbleMessageTypeReceived) {
            fileId = self.chMessage.FriendUserId;
        } else {
            fileId = self.chMessage.MineUserId;
        }
    }
    self.fileName = fileName;
    self.fileId = fileId;
    
    self.nameLabel.text = fileName;
    [self setUpButton];
    
    
    
    self.currentLenth = 0;
    
    if (self.chMessage.isMine == CHBubbleMessageTypeReceived) {
        if (self.chMessage.GroupId.length > 3) {
           self.filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:self.chMessage.fileName];
        } else {
            self.filePath = [[[ChildHoodService defaultService] personalDownLoadFilePathWithUserId:fileId] stringByAppendingPathComponent:self.chMessage.fileName];
        }
       
    } else {
        if (self.chMessage.GroupId.length > 3) {
            self.filePath = [[[ChildHoodService defaultService] groupUpLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:self.chMessage.fileName];
        } else {
            self.filePath = [[[ChildHoodService defaultService] personalUpLoadFilePathWithUserId:fileId] stringByAppendingPathComponent:self.chMessage.fileName];
        }

    }
    NSData *data2 = [NSData dataWithContentsOfFile:self.filePath];
    if (data2.length > 0 && data2.length < self.chMessage.fileLenth.floatValue) {
        self.progressView.progress =  data2.length / self.chMessage.fileLenth.floatValue;
        self.progressView.progressTintColor = RGBACOLORWithAlpha(246, 69, 53, 1.0);
        self.progressView.hidden = NO;
        self.progressLabel.hidden = NO;
        [self.progressLabel setText:[NSString stringWithFormat:@"下载暂停中 (%.2fK/%.2fK)",data2.length / 1024.0,self.chMessage.fileLenth.floatValue / 1024.0]];
        [self.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
        [self.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
        
    }

    
    BOOL flag = [self fileExistWithPath:self.filePath lenth:self.chMessage.fileLenth.integerValue];
    BOOL isCanOpen = [self checkFileTypeWithFileName:self.chMessage.fileName filePath:self.filePath];
    
    self.isCanOpen = isCanOpen;
    if (!flag) {
        self.downLoadButton.hidden = NO;
        self.openButton.hidden = YES;
        self.fowardButton.hidden = YES;
        self.otherButton.hidden = YES;
        self.oprateDownButton.hidden = YES;
        //判断文件是否过期
        if ([self isOverdateWithOverDate:self.chMessage.messageTime]) {
            
            [self.downLoadButton setBackgroundColor:RGBCOLOR(0x2c, 0xaa, 0xfe)];
            self.downLoadButton.userInteractionEnabled = YES;
        } else {
            [self.downLoadButton setTitle:@"下载原文件" forState:UIControlStateNormal];
            [self.downLoadButton setBackgroundColor:[UIColor lightGrayColor]];
            self.downLoadButton.userInteractionEnabled = NO;
            
            //bug6074 fixed by 荣则兵
            self.discLabel.text = @"";
            NSString *title = [NSString stringWithFormat:@"%.2fk",self.chMessage.fileLenth.floatValue / 1024.0];
            NSString *str2 = @"  已到期";
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",title,str2]];
            [attr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f],NSForegroundColorAttributeName:[UIColor grayColor]} range:NSMakeRange(0, title.length)];
            [attr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f],NSForegroundColorAttributeName:RGBACOLORWithAlpha(246, 69, 53, 1.0)} range:NSMakeRange(title.length, str2.length)];
            self.discLabel.attributedText = attr;
        }
    } else {
        self.downLoadButton.hidden = YES;
        self.discLabel.text = [NSString stringWithFormat:@"%.2fK",self.chMessage.fileLenth.floatValue / 1024.0];//bug6074 fixed by 荣则兵
         self.oprateDownButton.hidden = YES;
        if (isCanOpen) {
            self.openButton.hidden = NO;
            self.fowardButton.hidden = NO;
            self.otherButton.hidden = YES;
        } else {
            self.openButton.hidden = YES;
            self.fowardButton.hidden = NO;
            self.otherButton.hidden = NO;
        }
        
    }
}

//bug6074 fixed by 荣则兵
- (BOOL)isOverdateWithOverDate:(NSDate *)overDate
{
    NSTimeInterval time1 = [[NSDate date] timeIntervalSince1970] *1000 + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    NSTimeInterval sevenDay = 24 * 60 * 60 * 7;
//    NSTimeInterval sevenDay = 2 * 60 ;
    NSDate *overDate2 = [NSDate dateWithTimeInterval:sevenDay sinceDate:overDate];

    NSTimeInterval overTime = [overDate2 timeIntervalSince1970] * 1000;
    return time1 >= overTime ? NO:YES;
}

- (void)setUpButton
{
    self.downLoadButton = [self addButtonWithTitle:@"下载原文件" backColor:RGBCOLOR(0x2c, 0xaa, 0xfe) sel:@selector(checkNetWork)];
    self.otherButton = [self addButtonWithTitle:@"使用其他应用打开" backColor:RGBCOLOR(0x2c, 0xaa, 0xfe) sel:@selector(ortherOpen)];
    self.openButton = [self addButtonWithTitle:@"打开" backColor:RGBCOLOR(0x2c, 0xaa, 0xfe) sel:@selector(openFIle)];
    self.fowardButton = [self addButtonWithTitle:@"转发" backColor:RGBCOLOR(31, 191, 58) sel:@selector(fowardFile)];
    self.oprateDownButton = [self addButtonWithTitle:@"暂停下载" backColor:RGBCOLOR(246, 69, 53) sel:@selector(operateDownLoad:)];
}

- (void)operateDownLoad:(UIButton *)button
{
    __weak typeof(self) weakself = self;
     NSData *data = [NSData dataWithContentsOfFile:self.filePath];
    __block NSInteger dataLength = data.length;
     __block NetAndAudioModel *netAndAudio = nil;
    [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
        if ([self.chMessage.fileName isEqualToString:obj.serFileName]) {
            netAndAudio = obj;
            *stop = YES;
        }
    }];
    if (netAndAudio) {
        NSMutableURLRequest *request = (NSMutableURLRequest *)netAndAudio.operation.request;
        [request setValue:[NSString stringWithFormat:@"bytes=%zd-%zd",data.length,self.chMessage.fileLenth.longLongValue] forHTTPHeaderField:@"Range"];
        [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            dataLength = dataLength + bytesRead ;
            weakself.progressView.progress =  data.length / weakself.chMessage.fileLenth.floatValue;
            if (weakself.oprateDownButton.selected) {
                [weakself.progressLabel setText:[NSString stringWithFormat:@"下载暂停中 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
            } else {
                [weakself.progressLabel setText:[NSString stringWithFormat:@"文件正在下载 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
            }
        }];
        __block NetAndAudioModel *netAudio = netAndAudio;
        
        [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            weakself.downLoadButton.hidden = YES;
            
            [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            if (weakself.isCanOpen) {
                weakself.openButton.hidden = NO;
                weakself.fowardButton.hidden = NO;
                weakself.otherButton.hidden = YES;
                
            } else {
                weakself.openButton.hidden = YES;
                weakself.fowardButton.hidden = NO;
                weakself.otherButton.hidden = NO;
            }
            weakself.oprateDownButton.hidden = YES;
            weakself.progressView.hidden = YES;
            weakself.progressLabel.hidden = YES;
            weakself.discLabel.text = [NSString stringWithFormat:@"%.2fK",self.chMessage.fileLenth.floatValue / 1024.0];
            
             [weakself sendCompletedDownloadMessage];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            
            [MBProgressHUD showError:@"网络不可用!"];
            weakself.oprateDownButton.hidden = YES;
            weakself.downLoadButton.hidden = NO;
            [weakself.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
            [weakself.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
        }];

        
        
        button.selected = !button.selected;
        if (button.selected) {
            button.hidden = NO;
            self.progressView.progressTintColor = RGBCOLOR(246, 69, 53);
            [button setTitle:@"恢复下载" forState:UIControlStateSelected];
            [button setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
            [netAndAudio.operation pause];
        } else {
            
            self.oprateDownButton.hidden = YES;
            self.downLoadButton.hidden = NO;
            [self.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
            [self.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
           
            [self pauseCheckNetWork:netAndAudio];
        }
        
    } else {
//        NSLog(@"netAndAudio不存在!");
    }
}

- (void)pauseCheckNetWork:(NetAndAudioModel *)netAndAudio
{
    
    
    Reachability *r = [[CXmppMgr shareInstance] reachability];
    if ([r currentReachabilityStatus]==0) {
        // 没有网络连接
//        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"网络不可用"];
//        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [MBProgressHUD showError:@"网络不可用!"];
            self.oprateDownButton.hidden = YES;
            self.downLoadButton.hidden = NO;
            [self.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
            [self.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
//        }];
//        [alert show];
        
    }else if([r currentReachabilityStatus]==1){
        // 使用3G网络
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:[NSString stringWithFormat:@"非WiFi网络环境，确定下载%@ (%.2fK)",self.fileName,self.chMessage.fileLenth.floatValue / 1024.0]];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            self.oprateDownButton.hidden = NO;
            self.downLoadButton.hidden = YES;
            self.progressView.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
            [self.oprateDownButton setTitle:@"暂停下载" forState:UIControlStateNormal];
            [self.oprateDownButton setBackgroundColor:RGBACOLORWithAlpha(246, 69, 53, 1.0)];
            self.oprateDownButton.hidden = NO;
            
            [netAndAudio.operation resume];

        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
        
    }else if([r currentReachabilityStatus]==2){
        //        wifi
        self.oprateDownButton.hidden = NO;
        self.downLoadButton.hidden = YES;
        self.progressView.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
        [self.oprateDownButton setTitle:@"暂停下载" forState:UIControlStateNormal];
        [self.oprateDownButton setBackgroundColor:RGBACOLORWithAlpha(246, 69, 53, 1.0)];
        self.oprateDownButton.hidden = NO;
        
        [netAndAudio.operation resume];

        
    }
    
}

//bug 6101 yh
- (void)checkNetWork{
    
    
    Reachability *r = [[CXmppMgr shareInstance] reachability];
    if ([r currentReachabilityStatus]==0) {
        // 没有网络连接
//        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"网络不可用!"];
//        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//        }];
//        [alert show];
        [MBProgressHUD showError:@"网络不可用!"];

    }else if([r currentReachabilityStatus]==1){
        // 使用3G网络
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:[NSString stringWithFormat:@"非WiFi网络环境，确定下载%@ (%.2fK)",self.fileName,self.chMessage.fileLenth.floatValue / 1024.0]];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [self downLoadFile];
        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
    
    }else if([r currentReachabilityStatus]==2){
//        wifi
        [self downLoadFile];

    }
   
}
- (void)downLoadFile
{
    __weak typeof(self) weakself = self;
//    if ([self checkNetWork]) {
        self.downLoadButton.hidden = YES;
        self.openButton.hidden = YES;
        self.fowardButton.hidden = YES;
        self.otherButton.hidden = YES;
        self.oprateDownButton.hidden = NO;
        self.progressView.hidden = NO;
        self.progressLabel.hidden = NO;
        self.oprateDownButton.selected = NO;
        [self.oprateDownButton setTitle:@"暂停下载" forState:UIControlStateNormal];
        [self.oprateDownButton setBackgroundColor:RGBACOLORWithAlpha(246, 69, 53, 1.0)];
        self.progressView.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
    
    __block NetAndAudioModel *netAndAudio = nil;
    [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
        if ([weakself.chMessage.fileName isEqualToString:obj.serFileName]) {
            netAndAudio = obj;
            *stop = YES;
        }
    }];
    if (netAndAudio) {
        NSData *data1 = [NSData dataWithContentsOfFile:self.filePath];
        __block NSInteger dataLength = data1.length;
        NSMutableURLRequest *request = (NSMutableURLRequest *)netAndAudio.operation.request;
        [request setValue:[NSString stringWithFormat:@"bytes=%zd-%zd",data1.length,self.chMessage.fileLenth.longLongValue] forHTTPHeaderField:@"Range"];
        [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            dataLength = dataLength + bytesRead;
            weakself.progressView.progress =  dataLength / weakself.chMessage.fileLenth.floatValue;
            if (weakself.oprateDownButton.selected) {
                [weakself.progressLabel setText:[NSString stringWithFormat:@"下载暂停中 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
            } else {
                [weakself.progressLabel setText:[NSString stringWithFormat:@"文件正在下载 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
            }
        }];
        __block NetAndAudioModel *netAudio = netAndAudio;

        [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            weakself.downLoadButton.hidden = YES;
            
            [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            if (weakself.isCanOpen) {
                weakself.openButton.hidden = NO;
                weakself.fowardButton.hidden = NO;
                weakself.otherButton.hidden = YES;
                
            } else {
                weakself.openButton.hidden = YES;
                weakself.fowardButton.hidden = NO;
                weakself.otherButton.hidden = NO;
            }
            weakself.oprateDownButton.hidden = YES;
            weakself.progressView.hidden = YES;
            weakself.progressLabel.hidden = YES;
            weakself.discLabel.text = [NSString stringWithFormat:@"%.2fK",self.chMessage.fileLenth.floatValue / 1024.0];
            
             [weakself sendCompletedDownloadMessage];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            [MBProgressHUD showError:@"网络不可用!"];
            weakself.oprateDownButton.hidden = YES;
            weakself.downLoadButton.hidden = NO;
            [weakself.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
            [weakself.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
        }];
        [netAndAudio.operation resume];
        return;
    }
        if (self.chMessage.GroupId.length > 3) {
            NSData *data = [NSData dataWithContentsOfFile:self.filePath];
            __block NSInteger dataLength = data.length;
            [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:self.chMessage.fileName GroupId:self.chMessage.GroupId dataType:@"file" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                //          NSData *wavData;
                //          if ([self.chMessage.fileName hasSuffix:@".amr"] || [self.chMessage.fileName hasSuffix:@".wav"]) {
                //               wavData = [VoiceConverter amrToWav:responseObject];
                //              if (wavData == nil) {
                //                  wavData = responseObject;
                //              }
                //
                //          } else {
                //              wavData = responseObject;
                //          }
//                [[ChildHoodService defaultService] saveDownLoadFileWithFileName:self.fileName content:responseObject userId:self.fileId];
                weakself.downLoadButton.hidden = YES;
                if (weakself.isCanOpen) {
                    weakself.openButton.hidden = NO;
                    weakself.fowardButton.hidden = NO;
                    weakself.otherButton.hidden = YES;
                    
                } else {
                    weakself.openButton.hidden = YES;
                    weakself.fowardButton.hidden = NO;
                    weakself.otherButton.hidden = NO;
                }
                weakself.oprateDownButton.hidden = YES;
                weakself.progressView.hidden = YES;
                weakself.progressLabel.hidden = YES;
                weakself.discLabel.text = [NSString stringWithFormat:@"%.2fK",weakself.chMessage.fileLenth.floatValue / 1024.0];//bug6074 fixed by 荣则兵
                
                
                 [weakself sendCompletedDownloadMessage];
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                [MBProgressHUD showError:@"网络不可用!"];
                weakself.oprateDownButton.hidden = YES;
                weakself.downLoadButton.hidden = NO;
                [weakself.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
                [weakself.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                dataLength = dataLength +bytesRead;
                weakself.progressView.progress =  dataLength / weakself.chMessage.fileLenth.floatValue;
                if (weakself.oprateDownButton.selected) {
                    [weakself.progressLabel setText:[NSString stringWithFormat:@"下载暂停中 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
                } else {
                    [weakself.progressLabel setText:[NSString stringWithFormat:@"文件正在下载 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
                }
            } dataLenth:weakself.chMessage.fileLenth filePath:weakself.filePath];
            
        } else {
            NSData *data = [NSData dataWithContentsOfFile:self.filePath];
            __block NSInteger dataLength = data.length;
            [[CXmppRequestMgr shareInstance] downLoadeWithFileNmae:self.chMessage.fileName userId:self.fileId dataType:@"file" ssuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                weakself.downLoadButton.hidden = YES;
                if (weakself.isCanOpen) {
                    weakself.openButton.hidden = NO;
                    weakself.fowardButton.hidden = NO;
                    weakself.otherButton.hidden = YES;
                } else {
                    weakself.openButton.hidden = YES;
                    weakself.fowardButton.hidden = NO;
                    weakself.otherButton.hidden = NO;
                }
                weakself.oprateDownButton.hidden = YES;
                weakself.progressView.hidden = YES;
                weakself.progressLabel.hidden = YES;
                weakself.discLabel.text = [NSString stringWithFormat:@"%.2fK",weakself.chMessage.fileLenth.floatValue / 1024.0];//bug6074 fixed by 荣则兵
                
                [weakself sendCompletedDownloadMessage];
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                [MBProgressHUD showError:@"网络不可用!"];
                
                weakself.oprateDownButton.hidden = YES;
                weakself.downLoadButton.hidden = NO;
                [weakself.downLoadButton setTitle:@"恢复下载" forState:UIControlStateNormal];
                [weakself.downLoadButton setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
                
            } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                
                dataLength = dataLength + bytesRead;
                weakself.progressView.progress = dataLength / weakself.chMessage.fileLenth.floatValue;
                if (weakself.oprateDownButton.selected) {
                    [weakself.progressLabel setText:[NSString stringWithFormat:@"下载暂停中 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
                } else {
                    [weakself.progressLabel setText:[NSString stringWithFormat:@"文件正在下载 (%.2fK/%.2fK)",dataLength / 1024.0,weakself.chMessage.fileLenth.floatValue / 1024.0]];
                }
            } dataLenth:self.chMessage.fileLenth filePath:self.filePath];
        }
 
//    }
    
    
}



- (void)ortherOpen
{
    if (self.filePath.length > 0) {
        UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:self.filePath]];
        doInter.delegate = self;
        self.doInter = doInter;
        [doInter presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
        
    }

}

- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application
{
//    NSLog(@"heheheh");
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}


- (void)openFIle
{
//    if ([self.filePath rangeOfString:@".wav"].location != NSNotFound || [self.filePath rangeOfString:@".wav"].location != NSNotFound) {
//        return;
//    }
    if (self.filePath.length > 0) {
//        [self transformEncodingFromFilePath:self.filePath];
        UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:self.filePath]];
        doInter.delegate = self;
        [doInter presentPreviewAnimated:YES];

    }
}
//bug 8518 fixed by lixu
-(void)transformEncodingFromFilePath:(NSString*)filePath
{
    NSStringEncoding *useEncodeing = nil;
    NSString *body = [NSString stringWithContentsOfFile:filePath usedEncoding:useEncodeing error:nil];
    if (!body) {
        body = [NSString stringWithContentsOfFile:filePath encoding:0x80000632 error:nil];
    }
     if (!body) {
         body = [NSString stringWithContentsOfFile:filePath encoding:0x80000631 error:nil];
     }
    NSData *data = [body dataUsingEncoding:NSUTF16StringEncoding];
    [data writeToFile:filePath atomically:YES];
}
- (void)fowardFile
{
    CFileModel *fileModel = [[CFileModel alloc] init];
    fileModel.serverFileName = self.chMessage.fileName;
    fileModel.LocalFilePath = self.filePath;
    
    if (self.chMessage.GroupId.length > 3) {
        
         fileModel.FileName = [UIUtil getGroupFileNameWithServerFileName:fileModel.serverFileName];
    } else {
        fileModel.FileName = [UIUtil getFileNameWithServerFileName:fileModel.serverFileName];
    }

    [ChildHoodService defaultService].fileModel = fileModel;
    [ChildHoodService defaultService].imgLocalFilePath = nil;
    IMFowardController *foward = [[IMFowardController alloc] init];
    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:foward];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CGFloat viewWidth = HARDWARE_SCREEN_WIDTH;
    CGFloat viewHeight = HARDWARE_SCREEN_HEIGHT - 64;
    self.fileImgButton.frame = CGRectMake((viewWidth - 90) / 2.0, 110, 90, 90);
    self.nameLabel.frame = CGRectMake(30, CGRectGetMaxY(self.fileImgButton.frame), viewWidth - 60, 40);
    self.discLabel.frame = CGRectMake(30, CGRectGetMaxY(self.nameLabel.frame), viewWidth - 60, 30);
    self.progressView.frame = CGRectMake(30, CGRectGetMaxY(self.discLabel.frame) + 15, viewWidth - 60, 10);
    self.progressLabel.frame = CGRectMake(30, CGRectGetMaxY(self.progressView.frame), viewWidth - 60, 30);
    
    self.downLoadButton.frame = CGRectMake(15, viewHeight - 65, viewWidth - 30, 40);
    self.openButton.frame = CGRectMake(15, viewHeight - 65, (viewWidth - 45) / 2.0, 40);
    self.fowardButton.frame = CGRectMake(CGRectGetMaxX(self.openButton.frame) + 15, viewHeight - 65, (viewWidth - 45) / 2.0, 40);
    self.otherButton.frame = self.openButton.frame;
    self.oprateDownButton.frame = self.downLoadButton.frame;
    
}

- (UIButton *)addButtonWithTitle:(NSString *)title backColor:(UIColor *)backColor sel:(SEL)sel
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.textColor = [UIColor whiteColor];
    [button setBackgroundColor:backColor];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = Font16;
    [self.view addSubview:button];
    return button;
}

- (BOOL)checkFileTypeWithFileName:(NSString *)fileName filePath:(NSString *)filePath
{
    UIImage *image;
    NSString *nameStr = [fileName lowercaseString];
    
    NSString *fileIcon = [UIUtil getChatFileIconByName:nameStr];
    if ([fileIcon isEqualToString:@"icon-what"] || fileIcon == nil  || [fileIcon isEqualToString:@"icon-zip"]) {
        image = [UIImage imageNamed:fileIcon];
        [self.fileImgButton setImage:image forState:UIControlStateNormal];
        return NO;
    } else {
        image = [UIImage imageNamed:fileIcon];
        [self.fileImgButton setImage:image forState:UIControlStateNormal];
        return YES;
    }

}
-(BOOL)fileExistWithPath:(NSString *)path lenth:(NSInteger)lenth
{
    NSData* data = [NSData dataWithContentsOfFile:path];
    if(data != nil && data.length >= lenth) return YES;
    
    return NO;
}


- (void)back
{
    __block NetAndAudioModel *netAndAudio = nil;
    [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
        if ([self.chMessage.fileName isEqualToString:obj.serFileName]) {
            netAndAudio = obj;
            *stop = YES;
        }
    }];
    if (netAndAudio) {
        [netAndAudio.operation pause];
    }

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)sendCompletedDownloadMessage
{
    CContactMgr *conMgr = [[CContactMgr alloc] init];
    
    CContactModel *curUser = [conMgr loadContactWithUserId:self.chMessage.MineUserId];
    
    NSString *timeStamp = [UIUtil getCurrentTimeStamp];

    
    __block XMPPMessage *aMessage;
    long long filelenth = self.chMessage.fileLenth.longLongValue;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSString *fileName;
    if(self.chMessage.GroupId.length < 3)
    {
        CContactModel *member = [conMgr loadContactWithUserId:self.chMessage.FriendUserId];
        aMessage=[XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@@pcapp.%@",member.UserCode,[[CXmppMgr shareInstance] xmppStream].hostName]]];
        dict[@"toId"] = member.UserID;
        dict[@"toName"] = member.UserName;
        fileName = self.chMessage.fileName;
        
    } else {
        CGroupMgr *gMgr = [[CGroupMgr alloc] init];
        CGroupModel *group = [gMgr loadGroup:self.chMessage.GroupId];
        NSString* roomJid = [NSString stringWithFormat:@"%@@broadcast.%@",group.GroupId,[[CXmppMgr shareInstance] xmppStream].hostName];
        aMessage=[XMPPMessage messageWithType:@"groupchat" to:[XMPPJID jidWithString:roomJid]];
        dict[@"toId"] = group.GroupId;
        dict[@"groupId"] = group.GroupId;
        dict[@"toName"] = group.GroupName;
        fileName = self.chMessage.fileName;

    }
    [aMessage addAttributeWithName:@"from" stringValue:[NSString stringWithFormat:@"%@@%@",curUser.UserCode,[[CXmppMgr shareInstance] xmppStream].hostName]];
    
    dict[@"length"] = @(filelenth);
    dict[@"fromId"] = curUser.UserID;
    dict[@"body"] = self.fileName;
    dict[@"fileName"] = fileName;
    dict[@"nodeId"] = @"";
    dict[@"fromName"] = curUser.UserName;
    dict[@"status"] = @"";
    dict[@"type"] = @"automsg";
    dict[@"stream"] = @"";
    dict[@"companyId"] = M_STOREVALUE([[CFolderMgr shareInstance].serSettingMgr getSetting].companyId);
    dict[@"sendTime"] = timeStamp;
    dict[@"messageId"] = @"";
    
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:dict forKey:@"messageCommon"];
    NSString *body = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict1 options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    [aMessage addChild:[DDXMLNode elementWithName:@"body" stringValue:body]];
    
    [[CXmppMgr shareInstance] sendElement:aMessage];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
